// pages/index/index.js
const { formatDate, formatTimeHM, getTimeDiff, generateId } = require('../../utils/util.js')
const app = getApp()

Page({
  data: {
    userInfo: {},
    currentDate: '',
    filterType: 'day',
    tasks: [],
    completedCount: 0,
    totalCount: 0,
    totalTime: 0
  },

  onLoad() {
    this.setCurrentDate()
    this.loadTasks()
    this.checkLoginStatus()
  },

  onShow() {
    this.loadTasks()
    this.checkLoginStatus()
  },

  checkLoginStatus() {
    const userInfo = app.globalData.userInfo || {}
    this.setData({ userInfo })
  },

  onShow() {
    this.loadTasks()
  },

  setCurrentDate() {
    const today = new Date()
    this.setData({
      currentDate: formatDate(today)
    })
  },

  loadTasks() {
    // 模拟数据，实际应该从云数据库读取
    const tasks = [
      {
        id: generateId(),
        title: '完成项目需求分析',
        level: 1,
        completed: false,
        startTime: '09:00',
        endTime: '10:30',
        duration: 90,
        children: [
          {
            id: generateId(),
            title: '分析用户需求',
            level: 2,
            completed: true,
            startTime: '09:00',
            endTime: '09:30',
            duration: 30
          },
          {
            id: generateId(),
            title: '制定技术方案',
            level: 2,
            completed: false,
            startTime: '09:30',
            endTime: null,
            duration: null
          }
        ]
      },
      {
        id: generateId(),
        title: '开发任务管理功能',
        level: 1,
        completed: false,
        startTime: null,
        endTime: null,
        duration: null,
        children: []
      }
    ]

    this.calculateStats(tasks)
    this.setData({ tasks })
  },

  calculateStats(tasks) {
    let completedCount = 0
    let totalCount = 0
    let totalTime = 0

    const countTasks = (taskList) => {
      taskList.forEach(task => {
        totalCount++
        if (task.completed) {
          completedCount++
          totalTime += task.duration || 0
        }
        if (task.children && task.children.length > 0) {
          countTasks(task.children)
        }
      })
    }

    countTasks(tasks)
    this.setData({
      completedCount,
      totalCount,
      totalTime
    })
  },

  // 切换任务完成状态
  toggleTask(e) {
    const taskId = e.currentTarget.dataset.id
    const tasks = this.data.tasks
    this.toggleTaskRecursive(tasks, taskId)
    this.calculateStats(tasks)
    this.setData({ tasks })
  },

  toggleTaskRecursive(taskList, taskId) {
    for (let i = 0; i < taskList.length; i++) {
      if (taskList[i].id === taskId) {
        taskList[i].completed = !taskList[i].completed
        if (taskList[i].completed && !taskList[i].endTime) {
          taskList[i].endTime = formatTimeHM(new Date())
          taskList[i].duration = getTimeDiff(
            new Date(`2024-01-01 ${taskList[i].startTime}`),
            new Date(`2024-01-01 ${taskList[i].endTime}`)
          )
        }
        return true
      }
      if (taskList[i].children && taskList[i].children.length > 0) {
        if (this.toggleTaskRecursive(taskList[i].children, taskId)) {
          return true
        }
      }
    }
    return false
  },

  // 开始计时
  onStartTimer(e) {
    const taskId = e.currentTarget.dataset.id
    const tasks = this.data.tasks
    this.startTimerRecursive(tasks, taskId)
    this.setData({ tasks })
  },

  startTimerRecursive(taskList, taskId) {
    for (let i = 0; i < taskList.length; i++) {
      if (taskList[i].id === taskId) {
        taskList[i].startTime = formatTimeHM(new Date())
        taskList[i].endTime = null
        taskList[i].duration = null
        return true
      }
      if (taskList[i].children && taskList[i].children.length > 0) {
        if (this.startTimerRecursive(taskList[i].children, taskId)) {
          return true
        }
      }
    }
    return false
  },

  // 结束计时
  onStopTimer(e) {
    const taskId = e.currentTarget.dataset.id
    const tasks = this.data.tasks
    this.stopTimerRecursive(tasks, taskId)
    this.calculateStats(tasks)
    this.setData({ tasks })
  },

  stopTimerRecursive(taskList, taskId) {
    for (let i = 0; i < taskList.length; i++) {
      if (taskList[i].id === taskId) {
        taskList[i].endTime = formatTimeHM(new Date())
        taskList[i].duration = getTimeDiff(
          new Date(`2024-01-01 ${taskList[i].startTime}`),
          new Date(`2024-01-01 ${taskList[i].endTime}`)
        )
        return true
      }
      if (taskList[i].children && taskList[i].children.length > 0) {
        if (this.stopTimerRecursive(taskList[i].children, taskId)) {
          return true
        }
      }
    }
    return false
  },

  // 添加子任务
  onAddSubtask(e) {
    const parentId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/task/task?parentId=${parentId}&level=2`
    })
  },

  // 添加新任务
  onAddTask() {
    wx.navigateTo({
      url: '/pages/task/task?level=1'
    })
  },

  // 日期导航
  onPrevDay() {
    // 实现日期切换逻辑
    wx.showToast({
      title: '切换到前一天',
      icon: 'none'
    })
  },

  onNextDay() {
    // 实现日期切换逻辑
    wx.showToast({
      title: '切换到后一天',
      icon: 'none'
    })
  },

  // 设置筛选类型
  setFilterType(e) {
    const type = e.currentTarget.dataset.type
    this.setData({ filterType: type })
    // 根据筛选类型重新加载任务
    this.loadTasks()
  },

  // 用户头像点击
  onUserTap() {
    wx.navigateTo({
      url: '/pages/profile/profile'
    })
  }
})